import { PiniaPluginContext } from 'pinia'

// 定义插件选项接口
export interface MyPiniaPluginOptions {
  uid?: string
}

// 创建插件函数
export function myPiniaPlugin(context: PiniaPluginContext) {
  // 添加一个全局属性到所有 store
  return {
    // 添加一个创建时间戳
    createdAt: new Date().toISOString(),

    // 添加一个通用的 logger 方法
    log(message: string) {
      console.log(`[${context.store.$id}]: ${message}`)
    },

    // 添加一个通用的错误处理方法
    handleError(error: Error) {
      console.error(`[${context.store.$id}] Error:`, error.message)
      // 可以在这里添加错误上报逻辑
    }
  }
}

// 带选项的插件版本
export function myPiniaPluginWithOptions(options: MyPiniaPluginOptions = {}) {
  return (context: PiniaPluginContext) => {
    const uid = options.uid || Math.random().toString(36).substr(2, 9)

    return {
      // 添加唯一标识符
      uid,

      // 添加创建时间
      createdAt: new Date().toISOString(),

      // 添加调试方法
      debug() {
        console.log(`Store ${context.store.$id} debug info:`, {
          uid,
          state: context.store.$state,
          createdAt: this.createdAt
        })
      },

      // 添加持久化方法示例
      persist() {
        try {
          const state = JSON.stringify(context.store.$state)
          localStorage.setItem(`pinia-${context.store.$id}`, state)
          this.log('State persisted successfully')
        } catch (error) {
          this.handleError(error as Error)
        }
      },

      // 添加恢复状态方法
      restore() {
        try {
          const stored = localStorage.getItem(`pinia-${context.store.$id}`)
          if (stored) {
            const state = JSON.parse(stored)
            context.store.$patch(state)
            this.log('State restored successfully')
          }
        } catch (error) {
          this.handleError(error as Error)
        }
      }
    }
  }
}

// 更复杂的插件示例：自动保存和恢复状态
export function autoPersistPlugin(context: PiniaPluginContext) {
  const storeId = context.store.$id
  const storageKey = `pinia-auto-${storeId}`

  // 页面加载时尝试恢复状态
  const savedState = localStorage.getItem(storageKey)
  if (savedState) {
    try {
      const parsedState = JSON.parse(savedState)
      context.store.$patch(parsedState)
    } catch (e) {
      console.error(`Failed to restore state for ${storeId}:`, e)
    }
  }

  // 监听状态变化并自动保存
  context.store.$subscribe((mutation, state) => {
    try {
      localStorage.setItem(storageKey, JSON.stringify(state))
    } catch (e) {
      console.error(`Failed to save state for ${storeId}:`, e)
    }
  })

  return {
    // 添加清除持久化数据的方法
    clearPersisted() {
      localStorage.removeItem(storageKey)
    }
  }
}
